from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.work_order import WorkOrder
from app.models.material import MaterialUsage
from app.models.material import Material
from app.models.process_record import ProcessRecord
from app.models import db
from .work_orders_utils import (
    get_current_user, handle_db_error, 
    validate_work_order_permission
)
from app.utils.auth import require_permission
from datetime import datetime

work_orders_materials_bp = Blueprint('work_orders_materials', __name__)

@work_orders_materials_bp.route('/<int:work_order_id>/materials', methods=['GET'])
@jwt_required()
@require_permission('work_order.edit')
def get_work_order_materials(work_order_id):
    """获取工单材料使用列表"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(work_order_id)
        
        # 权限检查
        if not validate_work_order_permission(work_order, current_user, "view"):
            return jsonify({'error': '权限不足'}), 403
        
        # 获取材料使用记录
        material_usages = MaterialUsage.query.filter_by(work_order_id=work_order_id).all()
        
        materials_data = []
        for usage in material_usages:
            usage_dict = usage.to_dict()
            if usage.material:
                usage_dict['material'] = usage.material.to_dict()
            materials_data.append(usage_dict)
        
        return jsonify({
            'materials': materials_data
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_materials_bp.route('/<int:work_order_id>/materials', methods=['POST'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("添加材料使用记录")
def add_multiple_material_usage(work_order_id):
    """批量添加材料使用记录"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    materials_data = data.get('materials', [])
    if not materials_data:
        return jsonify({'error': '材料数据不能为空'}), 400
    
    added_materials = []
    
    for material_data in materials_data:
        material_id = material_data.get('material_id')
        quantity = material_data.get('quantity')
        
        if not material_id or not quantity:
            continue
        
        # 检查材料是否存在
        material = Material.query.get(material_id)
        if not material:
            continue
        
        # 检查库存
        if material.stock < quantity:
            return jsonify({
                'error': f'材料 {material.name} 库存不足，当前库存：{material.stock}，需要：{quantity}'
            }), 400
        
        # 创建材料使用记录
        material_usage = MaterialUsage(
            work_order_id=work_order_id,
            material_id=material_id,
            quantity=quantity,
            unit_price=material.price,
            total_price=material.price * quantity,
            used_by=current_user.id,
            used_at=datetime.utcnow(),
            notes=material_data.get('notes', '')
        )
        
        db.session.add(material_usage)
        
        # 更新材料库存
        material.stock -= quantity
        
        added_materials.append({
            'material_id': material_id,
            'material_name': material.name,
            'quantity': quantity,
            'unit_price': material.price,
            'total_price': material.price * quantity
        })
    
    # 创建处理记录
    if added_materials:
        materials_summary = ', '.join([f"{m['material_name']}({m['quantity']}{material.unit})" 
                                     for m in added_materials])
        
        process_record = ProcessRecord(
            work_order_id=work_order_id,
            user_id=current_user.id,
            action='材料录入',
            description=f'录入材料：{materials_summary}',
            created_at=datetime.utcnow()
        )
        db.session.add(process_record)
    
    db.session.commit()
    
    return jsonify({
        'message': f'成功添加 {len(added_materials)} 个材料使用记录',
        'materials': added_materials
    }), 201

@work_orders_materials_bp.route('/material-usage/<int:usage_id>', methods=['DELETE'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("删除材料使用记录")
def delete_material_usage(usage_id):
    """删除材料使用记录"""
    current_user = get_current_user()
    material_usage = MaterialUsage.query.get_or_404(usage_id)
    work_order = WorkOrder.query.get_or_404(material_usage.work_order_id)
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    # 恢复材料库存
    if material_usage.material:
        material_usage.material.stock += material_usage.quantity
    
    # 创建处理记录
    process_record = ProcessRecord(
        work_order_id=work_order.id,
        user_id=current_user.id,
        action='删除材料记录',
        description=f'删除材料使用记录：{material_usage.material.name if material_usage.material else "未知材料"} x{material_usage.quantity}',
        created_at=datetime.utcnow()
    )
    db.session.add(process_record)
    
    # 删除材料使用记录
    db.session.delete(material_usage)
    db.session.commit()
    
    return jsonify({'message': '材料使用记录删除成功'}), 200

@work_orders_materials_bp.route('/<int:work_order_id>/materials/<int:material_id>', methods=['PUT'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("更新材料使用记录")
def update_material_usage(work_order_id, material_id):
    """更新材料使用记录"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    # 查找材料使用记录
    material_usage = MaterialUsage.query.filter_by(
        work_order_id=work_order_id,
        material_id=material_id
    ).first_or_404()
    
    old_quantity = material_usage.quantity
    new_quantity = data.get('quantity', old_quantity)
    
    # 检查库存
    if material_usage.material:
        available_stock = material_usage.material.stock + old_quantity
        if available_stock < new_quantity:
            return jsonify({
                'error': f'材料库存不足，可用库存：{available_stock}，需要：{new_quantity}'
            }), 400
        
        # 更新库存
        material_usage.material.stock = available_stock - new_quantity
    
    # 更新材料使用记录
    material_usage.quantity = new_quantity
    material_usage.total_price = material_usage.unit_price * new_quantity
    material_usage.notes = data.get('notes', material_usage.notes)
    
    # 创建处理记录
    process_record = ProcessRecord(
        work_order_id=work_order_id,
        user_id=current_user.id,
        action='更新材料记录',
        description=f'更新材料使用：{material_usage.material.name if material_usage.material else "未知材料"} 数量从 {old_quantity} 改为 {new_quantity}',
        created_at=datetime.utcnow()
    )
    db.session.add(process_record)
    
    db.session.commit()
    
    return jsonify({
        'message': '材料使用记录更新成功',
        'material_usage': material_usage.to_dict()
    }), 200